<!-- 查询 agent -->
{{ $agentSQL := "* FROM agent WHERE id=? and status=1 order by status desc, sortNo desc" }}

{{ if eq .userType 1}}
  {{ $agentSQL ="* FROM agent WHERE id=? order by sortNo desc" }}
{{end}}

{{ $agent := selectOne "agent" $agentSQL .agentID }}
<!DOCTYPE html>
<html lang="{{locale}}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" document="IE=edge">
    <meta name="viewport" document="width=device-width, initial-scale=1">
    <title>{{$agent.Name}} - MINRAG</title>
    <link rel="stylesheet" href="{{basePath}}css/agent.css" />

</head>
<script>
    const basePath="{{basePath}}";
    const locale="{{locale}}";
</script>

<body>
    <div class="chat-container">
        <!-- 左侧历史聊天记录 -->
        <div class="history-panel">
            <div class="history-header">{{T "Chat History"}}</div>
            <div class="history-list">
                <div class="history-item">{{T "Current Chat"}}</div>
            </div>
        </div>

        <!-- 右侧聊天对话框 -->
        <div class="chat-panel">
            <div class="chat-header">{{$agent.Name}}</div>
            <div class="chat-messages">
                <div class="message ai-message"><p>{{$agent.Welcome}}</p></div>
            </div>
            <div class="chat-input">
                <input type="text" id="chat-input" placeholder='{{T "Send a message to MinRAG"}}' />
                <button id="send-btn">{{T "Send"}}</button>
            </div>
        </div>
    </div>
</body>
<script src="{{basePath}}js/jquery-3.7.1.min.js"></script>
<script src="{{basePath}}js/marked.min.js"></script>
<script>
function generateRandomNumber(n) {
    let random="";
    for (i = 0; i < n; i++) {
        random=random+""+Math.floor(Math.random()*10)
    }
    return random;
}
var roomID=generateRandomNumber(20)+"_{{.agentID}}";

var oldRoomID=localStorage.getItem("roomID");
if(!!oldRoomID){
    roomID=oldRoomID;
}else{
    localStorage.setItem("roomID", roomID);
}

$(document).ready(function() {


    $('#send-btn').click(function() {
        sendMessage();
    });
    $('#chat-input').keypress(function(e) {
        if (e.which == 13) { // Enter key
            sendMessage();
        }
    });
});

async function fetchSSE(aiMessageId,messageText) {
    let aiMarkdown=""
    try {
        const response = await fetch('{{basePath}}agent/sse', {
            method: 'POST',
            headers: {
                'Accept': 'text/event-stream',
                'Cache-Control':'no-cache',
                'Connection':'keep-alive',
            },
            body:JSON.stringify({
                "agentID":"{{.agentID}}",
                "roomID":roomID,
                "query": messageText,
            }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');

        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                console.log('Stream complete');
                break;
            }

            const chunk = decoder.decode(value, { stream: true });
            const lines=chunk.split("\n\n");
            for (const line of lines) {
                if (!line.startsWith('data: ')) {
                    continue;
                }
                const data = line.substring(6);
                if(data=="[DONE]"){
                    continue;
                }
                aiMarkdown=aiMarkdown+data;
                $("#"+aiMessageId+"_markdown").val(aiMarkdown)
                let dataHtml = marked.parse(aiMarkdown);
                // 移除 <p> 标签
                //dataHtml = dataHtml.replace(/<p>([\s\S]*?)<\/p>/g, '$1');
                document.getElementById(aiMessageId).innerHTML=dataHtml
            }
            
        }
    } catch (error) {
        console.error('Fetch stream failed:', error);
    }
}



function sendMessage() {
    const messageText = $('#chat-input').val().trim();
    if (!!!messageText) {
        return
    }
    const userMessage = $('<div class="message user-message"></div>').text(messageText);
    $('.chat-messages').append(userMessage);
    $('#chat-input').val('');

    const aiMessageId=new Date().getTime()+"_aiMessage"
    const aiMessage = $('<div class="message ai-message" id="'+aiMessageId+'"></div><input type="hidden" id="'+aiMessageId+'_markdown">');
    $('.chat-messages').append(aiMessage);
    $('.chat-messages').scrollTop($('.chat-messages')[0].scrollHeight);

    fetchSSE(aiMessageId,messageText)
  
}
</script>

</html>